<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-loading type="spinner" size="40" color="#4CAF50"></uni-loading>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 错误状态 -->
    <view v-else-if="error" class="error-container">
      <text class="error-icon">⚠️</text>
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="loadVillageIntro">重试</button>
    </view>
    
    <!-- 内容区域 -->
    <view v-else class="village-intro">
      <view class="intro-header">
        <text class="village-name">{{ villageData.title || '美丽乡村' }}</text>
        <text class="village-subtitle">{{ villageData.slogan || '和谐发展 共建共享' }}</text>
      </view>
      
      <!-- 人员介绍展示 -->
      <view v-if="staffList && staffList.length > 0" class="staff-section">
        <text class="section-title staff-title">人员介绍</text>
        <swiper 
          class="staff-swiper" 
          indicator-dots="true" 
          :autoplay="false"
          :current="currentStaffIndex"
          duration="500"
          @change="handleStaffSwiperChange"
        >
          <swiper-item v-for="(staff, index) in staffList" :key="index">
            <view class="staff-swiper-item">
              <view class="staff-avatar-wrapper">
                <image 
                  :src="getImageUrl(staff.imageUrl)" 
                  class="staff-avatar" 
                  mode="aspectFit"
                  @error="handleImageError"
                  @load="handleImageLoad"
                  lazy-load="true"
                />
              </view>
              <view class="staff-info">
                <text class="staff-name">{{ staff.name }}</text>
                <text class="staff-position">{{ staff.position }}</text>
                <view class="staff-phone" @click="callPhone(staff.phone)">
                  <text class="phone-icon">📞</text>
                  <text class="phone-number">{{ staff.phone }}</text>
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>
      
      <!-- 其他图片展示（如果有非人员图片） -->
      <view v-if="otherImages && otherImages.length > 0" class="village-images">
        <text class="section-title">乡村风貌</text>
        <swiper class="image-swiper" indicator-dots="true" autoplay="true" interval="3000" duration="500">
          <swiper-item v-for="(image, index) in otherImages" :key="index">
            <image 
              :src="getImageUrl(image)" 
              class="village-image" 
              mode="aspectFill"
              @error="handleImageError"
            />
          </swiper-item>
        </swiper>
      </view>
      
      <view class="intro-content">
        <view 
          v-for="(section, index) in villageData.sections" 
          :key="index" 
          class="intro-section"
        >
          <text class="section-title">{{ section.title }}</text>
          <text class="section-text">{{ section.content }}</text>
        </view>
      </view>
      
      <!-- 联系方式 -->
      <view v-if="villageData.contact" class="contact-section">
        <text class="contact-title">联系我们</text>
        <view class="contact-info">
          <view v-if="villageData.contact.phone" class="contact-item">
            <text class="contact-label">电话：</text>
            <text class="contact-value">{{ villageData.contact.phone }}</text>
          </view>
          <view v-if="villageData.contact.address" class="contact-item">
            <text class="contact-label">地址：</text>
            <text class="contact-value">{{ villageData.contact.address }}</text>
          </view>
          <view v-if="villageData.contact.email" class="contact-item">
            <text class="contact-label">邮箱：</text>
            <text class="contact-value">{{ villageData.contact.email }}</text>
          </view>
        </view>
      </view>
      
    </view>
  </view>
</template>

<script>
import { villageApi, utils } from '@/utils/api.js'

export default {
  data() {
    return {
      loading: true,
      error: null,
      isFirstLoad: true, // 标记是否是首次加载
      villageData: {
        title: '',
        slogan: '',
        sections: [],
        images: [],
        contact: {}
      },
      staffList: [], // 人员列表
      otherImages: [], // 其他图片（非人员介绍图片）
      currentStaffIndex: 0, // 当前人员索引
      staffDirection: 1, // 轮播方向：1 正向，-1 反向
      staffTimer: null // 轮播定时器
    }
  },
  onLoad() {
    // 首次加载时加载数据
    this.loadVillageIntro()
  },
  onShow() {
    // tab切换时刷新数据（但首次加载时已经在onLoad中加载过了，避免重复）
    if (!this.isFirstLoad) {
      console.log('村介绍页面显示，刷新数据')
      this.loadVillageIntro()
    } else {
      // 首次加载完成，标记为非首次加载
      this.isFirstLoad = false
    }
    // 启动轮播
    this.startStaffCarousel()
  },
  onHide() {
    // 页面隐藏时停止轮播
    this.stopStaffCarousel()
  },
  onUnload() {
    // 页面卸载时停止轮播
    this.stopStaffCarousel()
  },
  onPullDownRefresh() {
    this.loadVillageIntro().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    // 加载乡村介绍数据（无需token）
    async loadVillageIntro() {
      try {
        this.loading = true
        this.error = null
        
        const response = await villageApi.getVillageIntro()
        
        if (response.code === 200) {
          this.villageData = response.data || {}
          // 处理图片数据，解析人员信息
          this.processImages(this.villageData.images || [])
        } else {
          this.error = response.msg || '获取数据失败'
        }
      } catch (err) {
        console.error('加载乡村介绍失败:', err)
        this.error = '网络连接失败，请检查网络后重试'
      } finally {
        this.loading = false
      }
    },
    
    // 处理图片数据，解析人员信息
    processImages(images) {
      if (!images || images.length === 0) {
        this.staffList = []
        this.otherImages = []
        return
      }
      
      const staffList = []
      const otherImages = []
      
      images.forEach(imageUrl => {
        const staffInfo = this.parseStaffInfo(imageUrl)
        if (staffInfo) {
          // 是人员介绍图片
          staffList.push({
            imageUrl: imageUrl,
            name: staffInfo.name,
            position: staffInfo.position,
            phone: staffInfo.phone
          })
        } else {
          // 其他图片
          otherImages.push(imageUrl)
        }
      })
      
      this.staffList = staffList
      this.otherImages = otherImages
      
      // 重置轮播状态
      if (staffList.length > 0) {
        this.currentStaffIndex = 0
        this.staffDirection = 1
        // 启动轮播
        this.$nextTick(() => {
          this.startStaffCarousel()
        })
      }
    },
    
    // 解析图片路径中的人员信息
    // 路径格式：/profile/upload/2025/10/26/姓名-职务_联系电话.jpg
    parseStaffInfo(imagePath) {
      if (!imagePath) return null
      
      try {
        // 获取文件名（去掉路径和扩展名）
        const fileName = imagePath.split('/').pop()
        if (!fileName) return null
        
        // 去掉扩展名
        const nameWithoutExt = fileName.replace(/\.(jpg|jpeg|png|gif)$/i, '')
        
        // 按 '_' 分割，得到：姓名-职务 和 联系电话
        const parts = nameWithoutExt.split('_')
        if (parts.length < 2) return null
        
        const nameAndPosition = parts[0] // 姓名-职务
        const phone = parts[parts.length - 1] // 联系电话（取最后一部分，防止职务中有下划线）
        
        // 验证联系电话是否为数字
        if (!/^\d+$/.test(phone)) return null
        
        // 按 '-' 分割姓名和职务
        const namePosParts = nameAndPosition.split('-')
        const name = namePosParts[0] || ''
        const position = namePosParts.slice(1).join('-') || '工作人员' // 职务可能有多个部分，用'-'连接
        
        if (!name) return null
        
        return {
          name: name,
          position: position,
          phone: phone
        }
      } catch (err) {
        console.warn('解析人员信息失败:', imagePath, err)
        return null
      }
    },
    
    // 拨打电话
    callPhone(phone) {
      if (!phone) return
      
      uni.makePhoneCall({
        phoneNumber: phone,
        fail: (err) => {
          console.error('拨打电话失败:', err)
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 启动人员轮播
    startStaffCarousel() {
      // 先停止之前的定时器
      this.stopStaffCarousel()
      
      // 如果没有人员数据，不启动
      if (!this.staffList || this.staffList.length <= 1) {
        return
      }
      
      // 启动定时器
      this.staffTimer = setInterval(() => {
        this.nextStaff()
      }, 3000)
    },
    
    // 停止人员轮播
    stopStaffCarousel() {
      if (this.staffTimer) {
        clearInterval(this.staffTimer)
        this.staffTimer = null
      }
    },
    
    // 切换到下一个/上一个人员
    nextStaff() {
      if (!this.staffList || this.staffList.length === 0) return
      
      const total = this.staffList.length
      const nextIndex = this.currentStaffIndex + this.staffDirection
      
      // 判断是否需要改变方向
      if (nextIndex >= total) {
        // 到达最后一张后，改为反向
        this.staffDirection = -1
        this.currentStaffIndex = total - 2 // 下一张是倒数第二张
      } else if (nextIndex < 0) {
        // 回到第一张后，改为正向
        this.staffDirection = 1
        this.currentStaffIndex = 1 // 下一张是第二张
      } else {
        this.currentStaffIndex = nextIndex
      }
    },
    
    // 处理用户手动滑动
    handleStaffSwiperChange(e) {
      const currentIndex = e.detail.current
      this.currentStaffIndex = currentIndex
      
      // 根据当前位置判断方向
      const total = this.staffList.length
      if (currentIndex === 0) {
        // 在第一张，正向播放
        this.staffDirection = 1
      } else if (currentIndex === total - 1) {
        // 在最后一张，反向播放
        this.staffDirection = -1
      }
      
      // 重新启动轮播（用户滑动后继续自动播放）
      this.startStaffCarousel()
    },
    
    // 处理图片URL
    getImageUrl(imagePath) {
      return utils.getImageUrl(imagePath)
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      console.warn('图片加载失败:', e)
      // 可以设置默认头像
      // e.target.src = '/static/default-avatar.png'
    },
    
    // 处理图片加载完成
    handleImageLoad(e) {
      // 图片加载完成后的处理
      console.log('图片加载完成')
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

/* 错误状态样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  text-align: center;
}

.error-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.error-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
  line-height: 1.5;
}

.retry-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.retry-btn:active {
  background-color: #45a049;
}

.village-intro {
  background-color: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.intro-header {
  text-align: center;
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.village-name {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 10rpx;
}

.village-subtitle {
  display: block;
  font-size: 28rpx;
  color: #666;
}

/* 人员介绍样式 */
.staff-section {
  margin-bottom: 40rpx;
}

.staff-title {
  margin-bottom: 30rpx;
}

.staff-swiper {
  height: 680rpx;
  border-radius: 20rpx;
  overflow: hidden;
  background: linear-gradient(180deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(0, 0, 0, 0.05);
}

.staff-swiper-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 30rpx 30rpx 20rpx;
  height: 100%;
  box-sizing: border-box;
}

.staff-avatar-wrapper {
  width: 320rpx;
  height: 420rpx;
  border-radius: 20rpx;
  overflow: hidden;
  margin-bottom: 30rpx;
  border: 6rpx solid #f0f0f0;
  background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.staff-avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.staff-avatar-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(ellipse at center, rgba(255,255,255,0.3) 0%, transparent 70%);
  pointer-events: none;
  z-index: 1;
}

.staff-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.staff-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8rpx;
  text-align: center;
  letter-spacing: 0.5rpx;
  line-height: 1.2;
}

.staff-position {
  font-size: 26rpx;
  font-weight: bold;
  color: #666;
  margin-bottom: 8rpx;
  text-align: center;
  line-height: 1.4;
  padding: 0 20rpx;
  min-height: auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.staff-phone {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 36rpx;
  background-color: #f8f9fa;
  border-radius: 36rpx;
  font-size: 26rpx;
  color: #4CAF50;
  cursor: pointer;
  transition: background-color 0.2s;
}

.staff-phone:active {
  background-color: #e9ecef;
}

.phone-icon {
  font-size: 24rpx;
  margin-right: 6rpx;
}

.phone-number {
  font-size: 26rpx;
  color: #4CAF50;
  font-weight: 500;
}

/* 乡村图片样式 */
.village-images {
  margin-bottom: 40rpx;
}

.image-swiper {
  height: 400rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.village-image {
  width: 100%;
  height: 100%;
}

.intro-content {
  margin-bottom: 40rpx;
}

.intro-section {
  margin-bottom: 40rpx;
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
  border-left: 6rpx solid #4CAF50;
}

.section-text {
  display: block;
  font-size: 28rpx;
  line-height: 1.6;
  color: #666;
  text-align: justify;
}

/* 联系方式样式 */
.contact-section {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.contact-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
}

.contact-info {
  display: flex;
  flex-direction: column;
}

.contact-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15rpx;
}

.contact-item:last-child {
  margin-bottom: 0;
}


.contact-label {
  font-size: 26rpx;
  color: #666;
  min-width: 100rpx;
  flex-shrink: 0;
}

.contact-value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
  word-break: break-all;
}

</style>
